/**
 * @fileOverview multiSelect
 * @author huangtonger@aliyun.com
 */
const Page = require('../../base/');
const Global = require('../global');

Page.registerBehaviour('dragMultiSelect', diagram => {
  const graph = diagram.getGraph();
  const rootGroup = graph.getRootGroup();
  let startPoint;
  let delegation;
  diagram.css({
    cursor: Global.cursor.multiSelect
  });
  graph.behaviourOn('dragstart', ev => {
    if (ev.button === 2) {
      return;
    }
    startPoint = {
      x: ev.x,
      y: ev.y
    };
    delegation = rootGroup.addShape('rect', {
      attrs: Global.multiSelectRectStyle
    });
  });
  graph.behaviourOn('drag', ev => {
    if (!delegation) {
      return;
    }
    delegation.attr({
      x: Math.min(startPoint.x, ev.x),
      y: Math.min(startPoint.y, ev.y),
      width: Math.abs(ev.x - startPoint.x),
      height: Math.abs(ev.y - startPoint.y)
    });
    graph.draw();
  });
  graph.behaviourOn('dragend', () => {
    if (!delegation) {
      return;
    }
    const nodes = graph.getNodes();
    const nodeIds = nodes.map(node => {
      return node.id;
    });
    const delegationBox = delegation.getBBox();
    function method() {
      diagram.clearSelected();
      nodeIds.forEach(nodeId => {
        const node = graph.find(nodeId);
        const box = node.getBBox();
        if (
          box.minX > delegationBox.minX &&
          box.minY > delegationBox.minY &&
          box.maxX < delegationBox.maxX &&
          box.maxY < delegationBox.maxY
        ) {
          diagram.setSelected(node, true);
        }
      });
    }
    const editor = diagram.editor;
    if (editor) {
      editor.executeCommand(method);
    } else {
      method();
    }
    delegation.remove();
    diagram.changeMode('default');
    diagram.updateStatus();
    graph.draw();
    resetStatus();
  });
  graph.behaviourOn('canvas:mouseleave', () => {
    if (!delegation) {
      return;
    }
    delegation.remove();
    graph.draw();
    resetStatus();
  });
  function resetStatus() {
    diagram.css({
      cursor: Global.cursor.beforePanCanvas
    });
    startPoint = undefined;
    delegation = undefined;
  }
});
